const express = require('express');
const bcrypt = require('bcryptjs');
const db = require('../db');

const router = express.Router();

// 注册
router.post('/register', (req, res) => {
    const { username, password } = req.body;

    if (!username || !password) {
        return res.status(400).send('用户名和密码不能为空');
    }

    db.query('SELECT * FROM users WHERE username = ?', [username], (err, results) => {
        if (err) throw err;

        if (results.length > 0) {
            return res.status(400).send('用户名已存在');
        }

        const hashedPassword = bcrypt.hashSync(password, 10);
        db.query('INSERT INTO users (username, password) VALUES (?, ?)', [username, hashedPassword], (err) => {
            if (err) throw err;
            res.send('注册成功');
        });
    });
});


// 登录
router.post('/login', (req, res) => {
    const { username, password } = req.body;

    if (!username || !password) {
        return res.status(400).send('用户名和密码不能为空');
    }

    db.query('SELECT * FROM users WHERE username = ?', [username], (err, results) => {
        if (err) throw err;

        if (results.length === 0 || !bcrypt.compareSync(password, results[0].password)) {
            return res.status(401).send('用户名或密码错误');
        }

        req.session.userId = results[0].id;
        req.session.username = results[0].username;
        res.redirect('/data/home');
    });
});

module.exports = router;
